package com.ctshk.rpc.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ctshk.common.constant.ThirdUrlConstants;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.Currency;
import com.ctshk.common.enums.MemberType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.HttpUtils;
import com.ctshk.common.utils.MD5Util;
import com.ctshk.rpc.starvip.dto.UserMemberBasicInformationDTO;
import com.ctshk.rpc.starvip.dto.start_vip.transaction.LoyTransaction;
import com.ctshk.rpc.starvip.req.TransactionIntegralReq;
import com.ctshk.rpc.starvip.req.UserMemberBasicInformationReq;
import com.ctshk.rpc.starvip.service.IStarVipBusinessService;
import com.ctshk.rpc.system.constants.Constants;
import com.ctshk.rpc.system.dto.MainDataCurrencyListDTO;
import com.ctshk.rpc.system.dto.member.CardQueryDTO;
import com.ctshk.rpc.system.dto.member.ContactQueryDTO;
import com.ctshk.rpc.system.dto.member.CrmAccountDTO;
import com.ctshk.rpc.system.dto.member.CrmQueryDTO;
import com.ctshk.rpc.system.enums.CrmMemberQueryTypeEnum;
import com.ctshk.rpc.system.req.MainDataCurrencyListReq;
import com.ctshk.rpc.system.req.crm.member.CrmMemberQueryReq;
import com.ctshk.rpc.system.req.crm.member.CrmMemberReq;
import com.ctshk.rpc.system.req.crm.member.CrmMemberUpdatePointsReq;
import com.ctshk.rpc.system.service.ICrmMemberService;
import com.ctshk.rpc.system.service.IMainDataCurrencyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.rpc.RpcException;

import java.math.BigDecimal;
import java.util.HashMap;

/**
 * <p>
 * crm 会员积分接口
 * </p>
 *
 * @author 胡广
 * @since 2021/3/1
 */
@Slf4j
@DubboService
public class CrmMemberServiceImpl implements ICrmMemberService {
    @DubboReference
    IMainDataCurrencyService mainDataCurrencyService;
    @DubboReference
    IStarVipBusinessService starVipBusinessService;

    @Override
    public ContactQueryDTO queryMember(CrmMemberQueryReq crmMemberQueryReq) {
        // 第三方获取积分接口
        /*HashMap<String, String> paramMap = new HashMap<>();
        if (crmMemberQueryReq.getQueryType() == CrmMemberQueryTypeEnum.PHONE.getCode()) {
            paramMap.put("conCellPhNum", crmMemberQueryReq.getNumber());
        } else if (crmMemberQueryReq.getQueryType() == CrmMemberQueryTypeEnum.CERTIFICATE.getCode()) {
            paramMap.put("conxctsidentitynum", crmMemberQueryReq.getNumber()); //證件號碼
            paramMap.put("conxctsidentitytyp", crmMemberQueryReq.getCertificateType()); //證件類別碼 (取自證件類別列表)
        } else {
            throw new BusinessException(SystemError.SYSTEM_2103);
        }
        CrmQueryDTO member = findMember(paramMap);
        return member.getContact();*/
        UserMemberBasicInformationReq req = new UserMemberBasicInformationReq();
        if (crmMemberQueryReq.getQueryType() == CrmMemberQueryTypeEnum.PHONE.getCode()) {
            req.setPhone(crmMemberQueryReq.getNumber());
        } else if (crmMemberQueryReq.getQueryType() == CrmMemberQueryTypeEnum.CERTIFICATE.getCode()) {
            req.setCtsIdentityType(crmMemberQueryReq.getCertificateType());
            req.setCtsIdentityNum(crmMemberQueryReq.getNumber());
        }
        Result<UserMemberBasicInformationDTO> userMemberBasicInformation = starVipBusinessService.getUserMemberBasicInformation(req);
        if (!userMemberBasicInformation.isSuccess()) {
            // 查询会员信息异常
        }
        UserMemberBasicInformationDTO data = userMemberBasicInformation.getData();
        CrmAccountDTO crmAccountDTO = new CrmAccountDTO();
        crmAccountDTO.setMemberId(data.getMemberNumber());
        crmAccountDTO.setNameCn(data.getMemberName());
        crmAccountDTO.setConEmailAddr(data.getMemberEmail());
        crmAccountDTO.setMemberPointsValue(Long.valueOf(data.getPoint1Value()));
        /*if (data.getMemberTier() != null) {
            crmAccountDTO.setLevel(Integer.valueOf(data.getMemberTier()));
        }*/
        if (data.getMemberTierCode() != null) {
            crmAccountDTO.setLevel(Integer.valueOf(data.getMemberTierCode()));
        }
        return null;
    }

    @Override
    public CrmAccountDTO queryGroupMember(CrmMemberQueryReq crmMemberQueryReq) {
        UserMemberBasicInformationReq req = new UserMemberBasicInformationReq();
        if (crmMemberQueryReq.getQueryType() == CrmMemberQueryTypeEnum.PHONE.getCode()) {
            req.setPhone(crmMemberQueryReq.getNumber());
        } else if (crmMemberQueryReq.getQueryType() == CrmMemberQueryTypeEnum.CERTIFICATE.getCode()) {
            req.setCtsIdentityType(crmMemberQueryReq.getCertificateType());
            req.setCtsIdentityNum(crmMemberQueryReq.getNumber());
        }
        log.info("【CRM会员-查询账户信息】查询集团会员请求：{}", JSON.toJSONString(req));
        Result<UserMemberBasicInformationDTO> userMemberBasicInformation = null;
        try {
            userMemberBasicInformation = starVipBusinessService.getUserMemberBasicInformation(req);
        } catch (RpcException e) {
            log.info("【CRM会员-查询账户信息】查询集团会员响应：{}");
        } catch (Exception e) {
            log.info("【CRM会员-查询账户信息】查询集团会员响应：{}");
        }
        log.info("【CRM会员-查询账户信息】查询集团会员响应：{}", JSON.toJSONString(userMemberBasicInformation));
        if (!userMemberBasicInformation.isSuccess()) {
            // 查询会员信息异常
            log.error("【CRM会员-查询账户信息】查询集团会员失败");
        }
        UserMemberBasicInformationDTO data = userMemberBasicInformation.getData();
        CrmAccountDTO crmAccountDTO = new CrmAccountDTO();
        crmAccountDTO.setMemberId(data.getMemberNumber());
        crmAccountDTO.setNameCn(data.getMemberName());
        crmAccountDTO.setConEmailAddr(data.getMemberEmail());
        crmAccountDTO.setMemberPointsValue(Long.valueOf(data.getPoint1Value()));
        /*if (data.getMemberTier() != null) {
            crmAccountDTO.setLevel(Integer.valueOf(data.getMemberTier()));
        }*/
        if (data.getMemberTierCode() != null) {
            crmAccountDTO.setLevel(Integer.valueOf(data.getMemberTierCode()));
        }
        return crmAccountDTO;
    }

    /*@Override
    public CrmAccountDTO queryAccountDetail(CrmMemberQueryReq crmMemberQueryReq) {
        // 第三方获取积分接口
        HashMap<String, String> paramMap = new HashMap<>();

        if (crmMemberQueryReq.getQueryType() == CrmMemberQueryTypeEnum.PHONE.getCode()) {
            paramMap.put("conCellPhNum", crmMemberQueryReq.getNumber());
        } else if (crmMemberQueryReq.getQueryType() == CrmMemberQueryTypeEnum.CERTIFICATE.getCode()) {
            paramMap.put("conxctsidentitynum", crmMemberQueryReq.getNumber()); //證件號碼
            paramMap.put("conxctsidentitytyp", crmMemberQueryReq.getCertificateType()); //證件類別碼 (取自證件類別列表)
        } else {
            throw new BusinessException(SystemError.SYSTEM_2103);
        }
        // 查询会员信息
        CrmQueryDTO crmQueryDTO = findMember(paramMap);
        if (crmQueryDTO.getSystemError() == null) {
            //返回会员信息
            return buildCrmAccountDTO(crmQueryDTO.getContact(), MemberType.STAR_CLUB_MEMBER);
        }
        // 查询客户信息
        crmQueryDTO = findCustomer(paramMap);
        if (crmQueryDTO.getSystemError() != null) {
            throw new BusinessException(crmQueryDTO.getSystemError());
        }
        // 返回客户信息
        return buildCrmAccountDTO(crmQueryDTO.getContact(), MemberType.ORDINARY_MEMBER);
    }*/
    @Override
    public CrmAccountDTO queryAccountDetail(CrmMemberQueryReq crmMemberQueryReq) {
        UserMemberBasicInformationReq req = new UserMemberBasicInformationReq();
        if (crmMemberQueryReq.getQueryType() == CrmMemberQueryTypeEnum.PHONE.getCode()) {
            req.setPhone(crmMemberQueryReq.getNumber());
        } else if (crmMemberQueryReq.getQueryType() == CrmMemberQueryTypeEnum.CERTIFICATE.getCode()) {
            req.setCtsIdentityType(crmMemberQueryReq.getCertificateType());
            req.setCtsIdentityNum(crmMemberQueryReq.getNumber());
        }
        log.info("【CRM会员-查询账户信息】查询集团会员请求：{}", JSON.toJSONString(req));
        Result<UserMemberBasicInformationDTO> userMemberBasicInformation = null;
        try {
            userMemberBasicInformation = starVipBusinessService.getUserMemberBasicInformation(req);
        } catch (RpcException e) {
            log.info("【CRM会员-查询账户信息】查询集团会员响应：{}");
        } catch (Exception e) {
            log.info("【CRM会员-查询账户信息】查询集团会员响应：{}");
        }
        log.info("【CRM会员-查询账户信息】查询集团会员响应：{}", JSON.toJSONString(userMemberBasicInformation));
        if (!userMemberBasicInformation.isSuccess()) {
            // 查询会员信息异常
            log.error("【CRM会员-查询账户信息】查询集团会员失败");
        }
        UserMemberBasicInformationDTO data = userMemberBasicInformation.getData();
        CrmAccountDTO crmAccountDTO = new CrmAccountDTO();
        crmAccountDTO.setMemberId(data.getMemberNumber());
        crmAccountDTO.setNameCn(data.getMemberName());
        crmAccountDTO.setConEmailAddr(data.getMemberEmail());
        crmAccountDTO.setConCellPhNum(data.getMemberPhone());
        crmAccountDTO.setMemberPointsValue(Long.valueOf(data.getPoint1Value()));
        if (StringUtils.isNotBlank(data.getMemberTier())) {
            crmAccountDTO.setLevelName(data.getMemberTier());
        }
        if (data.getMemberTierCode() != null) {
            crmAccountDTO.setLevel(Integer.valueOf(data.getMemberTierCode()));
        }
        return crmAccountDTO;
    }

    @Override
    public CrmMemberReq updatePoints(CrmMemberUpdatePointsReq crmMemberUpdatePointsReq, ContactQueryDTO contactQuery) {
        return null;
    }

    /**
     * 构建CRM账号信息
     *
     * @param contact
     * @param type    1:查询会员类型，2:查询账户类型
     * @return
     */
    private CrmAccountDTO buildCrmAccountDTO(ContactQueryDTO contact, MemberType type) {
        CrmAccountDTO crmAccountDTO = EntityUtil.copy(contact, CrmAccountDTO.class);
        crmAccountDTO.setNameCn(contact.getConLastName() + contact.getConFstName());
        crmAccountDTO.setNameEn(contact.getConXCtsFstName() + contact.getConMidName() + contact.getConXCtsLastname());
        if (MemberType.STAR_CLUB_MEMBER == type) {
            // 构建会员信息
            crmAccountDTO.setMemberId(contact.getMember().getGroupId());
            crmAccountDTO.setMemberPointsValue(contact.getMember().getPoint1Value());
            crmAccountDTO.setType(MemberType.STAR_CLUB_MEMBER.getCode());
        } else {
            crmAccountDTO.setType(MemberType.ORDINARY_MEMBER.getCode());
        }
        crmAccountDTO.setLevel(1);//默认等级1，日后CRM接口提供了LEVEL再调整
        return crmAccountDTO;
    }

    /*@Override
    public CrmMemberReq updatePoints(CrmMemberUpdatePointsReq crmMemberUpdatePointsReq, ContactQueryDTO contactQuery) {
        CrmMemberReq crmMemberReq = EntityUtil.copy(crmMemberUpdatePointsReq, CrmMemberReq.class);
        String url = null;
        if (crmMemberUpdatePointsReq.getUpdateType() == 1) {
            //加积分
            crmMemberReq.setXCtsPtName("消费积分");
            url = ThirdUrlConstants.CRM_MEMBER_ADD_URL;
        } else if (crmMemberUpdatePointsReq.getUpdateType() == 2) {
            //减积分
            crmMemberReq.setXCtsPtName("已使用积分");
            url = ThirdUrlConstants.CRM_MEMBER_DEDUCT_URL;
        } else {
            throw new BusinessException(SystemError.SYSTEM_2103);
        }
        crmMemberReq.setGroupId(contactQuery.getMember().getGroupId());//集团会员编号
        for (CardQueryDTO card : contactQuery.getCards()) {
            crmMemberReq.setXCtsTxnMemCd(card.getCrdCardNum()); //会员卡号
        }
        if (StringUtils.isBlank(crmMemberReq.getXCtsTxnMemCd())) {
            // 会员卡号不存在
            throw new BusinessException(SystemError.SYSTEM_2104);
        }
        crmMemberReq.setSubTypeCd("Product");
        crmMemberReq.setPointInternalname("港中旅积分");
        crmMemberReq.setProgramName("港中旅集团忠诚度计划");
        crmMemberReq.setPartnerAccntName("2199");
        crmMemberReq.setQualFlg("N");
        crmMemberReq.setCurcyCd("HKD");
        crmMemberReq.setStatusCd("已入队列");
        crmMemberReq.setXCtsQualifyTxn("N");
        crmMemberReq.setPartNumber(crmMemberReq.getProdName());
        crmMemberReq.setXCtsOrderNum(crmMemberReq.getTxnNum());
        crmMemberReq.setHkcrmMemberId(contactQuery.getConIntegrationId());
        crmMemberReq.setModifyUserid(crmMemberReq.getCreateUserid());
        try {
            String crmMemberReqJSONStr = JSON.toJSONString(crmMemberReq);
            log.info("【CRM会员】, update member points request param:{}", crmMemberReqJSONStr);
            String findMemberResult = HttpUtils.sendHttpSslPost(url, crmMemberReqJSONStr);
            log.info("【CRM会员】, update member points request result:{}", findMemberResult);
            CrmMemberReq crmMemberDto = JSON.parseObject(findMemberResult, CrmMemberReq.class);
            return crmMemberDto;
        } catch (Exception e) {
            log.error("【CRM会员】查询会员信息失败！to=[{}],msg=[{}]", e);
            throw new BusinessException(SystemError.SYS_437);
        }
    }*/
    @Override
    public CrmMemberReq updatePoints(CrmMemberUpdatePointsReq crmMemberUpdatePointsReq) {
        CrmMemberReq crmMemberReq = EntityUtil.copy(crmMemberUpdatePointsReq, CrmMemberReq.class);
        String url = null;
        if (crmMemberUpdatePointsReq.getUpdateType() == 1) {
            //加积分
            crmMemberReq.setXCtsPtName("消费积分");
            url = ThirdUrlConstants.CRM_MEMBER_ADD_URL;
        } else if (crmMemberUpdatePointsReq.getUpdateType() == 2) {
            //减积分
            crmMemberReq.setXCtsPtName("已使用积分");
            url = ThirdUrlConstants.CRM_MEMBER_DEDUCT_URL;
        } else {
            throw new BusinessException(SystemError.SYSTEM_2103);
        }
//        crmMemberReq.setGroupId(contactQuery.getMember().getGroupId());//集团会员编号
//        for (CardQueryDTO card : contactQuery.getCards()) {
//            crmMemberReq.setXCtsTxnMemCd(card.getCrdCardNum()); //会员卡号
//        }
//        if (StringUtils.isBlank(crmMemberReq.getXCtsTxnMemCd())) {
//            // 会员卡号不存在
//            throw new BusinessException(SystemError.SYSTEM_2104);
//        }
        crmMemberReq.setSubTypeCd("Product");
        crmMemberReq.setPointInternalname("港中旅积分");
        crmMemberReq.setProgramName("港中旅集团忠诚度计划");
        crmMemberReq.setPartnerAccntName("2199");
        crmMemberReq.setQualFlg("N");
        crmMemberReq.setCurcyCd("HKD");
        crmMemberReq.setStatusCd("已入队列");
        crmMemberReq.setXCtsQualifyTxn("N");
        crmMemberReq.setPartNumber(crmMemberReq.getProdName());
        crmMemberReq.setXCtsOrderNum(crmMemberReq.getTxnNum());
//        crmMemberReq.setHkcrmMemberId(contactQuery.getConIntegrationId());
        crmMemberReq.setModifyUserid(crmMemberReq.getCreateUserid());
        String crmMemberReqJSONStr = JSON.toJSONString(crmMemberReq);
        log.info("【CRM会员-更新积分】, crm member req JSON:{}", crmMemberReq);
//            String result = HttpUtils.sendHttpSslPost(url, crmMemberReqJSONStr);
        TransactionIntegralReq transactionIntegralReq = new TransactionIntegralReq();
        transactionIntegralReq.setCtsLogin(crmMemberUpdatePointsReq.getCtsLogin());
        transactionIntegralReq.setCtsPassword(crmMemberUpdatePointsReq.getCtsPassword());
        transactionIntegralReq.setOrderNumber(crmMemberUpdatePointsReq.getTxnNum());
        transactionIntegralReq.setPoints(crmMemberUpdatePointsReq.getNumPoints());
        try {
            log.info("【CRM会员-更新积分】, transaction integral request param:{}", transactionIntegralReq);
            Result result = starVipBusinessService.transactionIntegral(transactionIntegralReq);
            log.info("【CRM会员-更新积分】, transaction integral  request result:{}", result);
//            CrmMemberReq crmMemberDto = JSON.parseObject(result, CrmMemberReq.class);
            return null;
        } catch (Exception e) {
            log.error("【CRM会员-更新积分】查询会员信息失败！to=[{}],msg=[{}]", e);
            throw new BusinessException(SystemError.SYS_437);
        }
    }

    @Override
    public BigDecimal queryPointsToHkd() {
        //查询人民币汇率
        MainDataCurrencyListReq mainDataCurrencyListReq = new MainDataCurrencyListReq();
        mainDataCurrencyListReq.setName(Currency.CNY.getSymbol());
        PageResponse<MainDataCurrencyListDTO> list = mainDataCurrencyService.list(mainDataCurrencyListReq);
        if (CollectionUtils.isEmpty(list.getRecords())) {
            throw new BusinessException(SystemError.AIREXPRESS_ORDER_60003);
        }
        BigDecimal crmExchangeRate = list.getRecords().get(0).getCrmExchangeRate();
        BigDecimal amountHkd = crmExchangeRate.divide(Constants.POINTS_TO_CNY, BigDecimal.ROUND_HALF_UP, 4);
        return amountHkd;
    }

    @Override
    public CrmMemberReq updatePointsByStarVip(CrmMemberUpdatePointsReq crmMemberUpdatePointsReq, ContactQueryDTO contactQuery) {
        return updatePointsByStarVip(crmMemberUpdatePointsReq);
    }

    @Override
    public CrmMemberReq updatePointsByStarVip(CrmMemberUpdatePointsReq crmMemberUpdatePointsReq) {
        //CrmMemberReq crmMemberReq = EntityUtil.copy(crmMemberUpdatePointsReq, CrmMemberReq.class);
        TransactionIntegralReq transactionIntegralReq = new TransactionIntegralReq();
        if (crmMemberUpdatePointsReq.getUpdateType() == 1) {
            //加积分
            transactionIntegralReq.setTransactionType("1");
        } else if (crmMemberUpdatePointsReq.getUpdateType() == 2) {
            //减积分
            transactionIntegralReq.setTransactionType("2");
        } else {
            throw new BusinessException(SystemError.SYSTEM_2103);
        }


        transactionIntegralReq.setCtsLogin(crmMemberUpdatePointsReq.getCtsLogin());
        transactionIntegralReq.setCtsPassword(MD5Util.stringMd5(crmMemberUpdatePointsReq.getCtsPassword()));
        transactionIntegralReq.setOrderNumber(crmMemberUpdatePointsReq.getTxnNum());
        transactionIntegralReq.setPoints(crmMemberUpdatePointsReq.getNumPoints());
        try {
            log.info("【CRM会员-更新积分】, transaction integral request param:{}", transactionIntegralReq);
            Result result = starVipBusinessService.transactionIntegralThree(transactionIntegralReq);
            log.info("【CRM会员-更新积分】, transaction integral  request result:{}", result);
            return null;
        } catch (Exception e) {
            log.error("【CRM会员-更新积分】查询会员信息失败！to=[{}],msg=[{}]", e);
            throw new BusinessException(SystemError.SYS_437);
        }
    }
}
